import { utils, write, read } from 'xlsx';
import { saveAs } from 'file-saver';

// 类型定义
type ExcelData = any[][];
type ImportCallback = (data: ExcelData) => void;

// 导出Excel（支持自定义表头）
export const exportExcel = (
    data: ExcelData,
    fileName: string | null | undefined = 'export.xlsx',
    sheetName: string = 'Sheet1'
) => {
    const worksheet = utils.aoa_to_sheet(data);
    const workbook = utils.book_new();
    utils.book_append_sheet(workbook, worksheet, sheetName);
    const buffer = write(workbook, { bookType: 'xlsx', type: 'array' });
    const blob = new Blob([buffer], { type: 'application/octet-stream' });
    saveAs(blob, fileName);
};

// 导入Excel处理
export const handleExcelImport = (file: File, callback: ImportCallback) => {
    const reader = new FileReader();

    reader.onload = (e) => {
        try {
            const data = new Uint8Array(e.target?.result as ArrayBuffer);
            const workbook = read(data, { type: 'array' });
            const worksheet = workbook.Sheets[workbook.SheetNames];
            const jsonData = utils.sheet_to_json(worksheet, { header: 1 });
            callback(jsonData);
        } catch (error) {
            console.error('文件解析失败:', error);
        }
    };
    reader.readAsArrayBuffer(file);
};

export const validateData = (headers:any[],tableHeaders:[]) => {
    return (
        headers.length === tableHeaders.length &&
        headers.every((h, i) => h === tableHeaders[i])
    );
};